package com.heima.article.listener;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * 完成对发布文章上下架状态变更
 *
 * @author: itheima
 * @create: 2021-12-28 11:49
 */
@Slf4j
@Component
public class ArticleUpDownListener {

    @Autowired
    private IApArticleService apArticleService;

    /**
     * 监听到文章上下架话题
     * 完成修改发布文章上下架状态
     */
    @KafkaListener(topics = "${topic.upDownTopic}")
    public void handlerMsg(ConsumerRecord<String, String> consumerRecord) {
        //1.获取发送消息内容
        String value = consumerRecord.value();

        //2.将获取到数据转为Map
        if (StringUtils.isNotBlank(value)) {
            log.info("【文章微服务】监听到上下架消息：{}", value);
            //2.1 获取生产者发送消息数据
            HashMap hashMap = JSONObject.parseObject(value, HashMap.class);
            Long articleId = (Long) hashMap.get("articleId");
            boolean isDown = (boolean) hashMap.get("isDown");
            //2.2 更新文章表状态
            LambdaUpdateWrapper<ApArticle> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ApArticle::getId, articleId);
            updateWrapper.set(ApArticle::getIsDown, isDown);
            apArticleService.update(updateWrapper);
        }
    }


}
